import {
  USER_ACCESS,
  INVITE_FROM_TOKEN,
  ACTIVE_SHARE_KEY,
  PASSIVE_SHARE_KEY
} from '../constants/sitevars'
import { cryptoStore } from './cryptoFactory'
const IgnoreParam = ['realPath', 'title', 'imageUrl']
const app = getApp();

/**
 * @param { object } extraParam 需要在页面内固定的分享参数
 * @param { string } extraParam.realPath 需要在页面内固定的指定路由
 * @returns { path } 路由页面地址
 */
function getShareConfig(extraParam = {}) {
  const { token } = cryptoStore.getStorageSync(USER_ACCESS)
  const currentPages = getCurrentPages()
  const lastPage = currentPages[currentPages.length - 1]
  const { route, options } = lastPage;
  const timestamp = Date.now();
  const { shared_key = 'share_mini', title } = extraParam;

  // 生成安全的路径参数
  let pathCpn = [];
  // 筛选和添加options中的参数
  Object.keys(options || {}).forEach(k => {
    if (k !== INVITE_FROM_TOKEN && !extraParam.hasOwnProperty(k)) {
      pathCpn.push(`${k}=${encodeURIComponent(options[k])}`);
    }
  });
  // 添加extraParam中的参数
  Object.keys(extraParam).forEach(et => {
    if (IgnoreParam.indexOf(et) === -1) {
      pathCpn.push(`${et}=${encodeURIComponent(extraParam[et])}`);
    }
  });
  pathCpn = [
    ...pathCpn,
    `shared_key=${encodeURIComponent(shared_key)}`,
    `${INVITE_FROM_TOKEN}=${encodeURIComponent(token)}`,
    `timestamp=${encodeURIComponent(timestamp)}`
  ];
  const path = (extraParam.realPath || route) + '?' + pathCpn.join("&");

  const shareMap = cryptoStore.getStorageSync(ACTIVE_SHARE_KEY) || {}
  shareMap[route] = { timestamp, noticed: false };
  cryptoStore.setStorageSync(ACTIVE_SHARE_KEY, shareMap);
  console.log(path);
  return { title, ...extraParam, path, };
}

// 移除过期的邀请记录
function cleanInvitedMap(invitedMap, nowTime) {
  for (const path in invitedMap) {
    if (invitedMap.hasOwnProperty(path)) {
      const timeKeys = invitedMap[path];
      for (const timeStampKey in timeKeys) {
        if (timeKeys.hasOwnProperty(timeStampKey) && nowTime - Number(timeStampKey) > REMOVE_DAY) {
          delete timeKeys[timeStampKey];
        }
      }
    }
  }
  return invitedMap;
}
// 更新邀请记录
function updateInvitedMap(invitedMap, route, timestamp, url) {
  if (!invitedMap[route]) {
    invitedMap[route] = {};
  }
  if (!invitedMap[route][timestamp]) {
    invitedMap[route][timestamp] = [];
  }
  if (!invitedMap[route][timestamp].includes(url)) {
    invitedMap[route][timestamp].push(url);
  }
  return invitedMap;
}
const IGNORE_DAY = 1 * 24 * 60 * 60 * 1000
const REMOVE_DAY = 2 * 24 * 60 * 60 * 1000;

/**
 * @summary 首先当前路由是由于别人分享过来的，检测是否还有效
 * @param {string} url 请求的地址,同一个页面可能有多个请求，所以放在数组
 * @constant IGNORE_DAY 分享的链接 IGNORE_DAY 之后也不统计了
 * @constant REMOVE_DAY 如果是用户清理微信缓存, REMOVE_DAY 以后清理点击过就清理缓存，没有点击过就触发统计
 * @waning REMOVE_DAY > IGNORE_DAY
 * @JOKER  没那么巧刚好一天内连续清理缓存刷分享次数吧
 * @returns {boolean}
 */
function isInvitationUsable(url) {
  try {
    let currentPages = getCurrentPages();
    if (currentPages.length === 0) {
      // 处理当前页面栈为空的情况
      return false;
    }
    const { options = {}, route } = currentPages[currentPages.length - 1];
    const userAccessToken = cryptoStore.getStorageSync(USER_ACCESS);
    if (!userAccessToken) {
      // 处理用户访问令牌不存在的情况
      return false;
    }
    const { token } = userAccessToken;
    const invitedBy = options[INVITE_FROM_TOKEN];
    let invitedMap = {};
    if (invitedBy && invitedBy !== token) {
      invitedMap = cryptoStore.getStorageSync(PASSIVE_SHARE_KEY) || {};
      if (typeof options.timestamp !== 'number') {
        // 如果时间戳不存在或不是数字，则无法处理
        return false;
      }
      const nowTime = Date.now();
      // 清理过期条目
      invitedMap = cleanInvitedMap(invitedMap, nowTime);
      const notIgnore = nowTime - options.timestamp < IGNORE_DAY;
      if (notIgnore) {
        // 初始化或更新邀请映射
        invitedMap = updateInvitedMap(invitedMap, route, options.timestamp, url);
        cryptoStore.setStorageSync(PASSIVE_SHARE_KEY, invitedMap);
        return true;
      }
    }
    cryptoStore.setStorageSync(PASSIVE_SHARE_KEY, invitedMap); // 保持存储同步
    return false;
  } catch (error) {
    console.error("Error processing invitation usability:", error);
    return false; // 在异常情况下保守返回false
  }
}

export {
  getShareConfig,
  isInvitationUsable,

}